package com.uduew.sjd.utils

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.telephony.TelephonyManager
import android.text.format.Formatter
import androidx.core.content.ContextCompat
import com.uduew.sjd.api.SubmitDeviceInfoApi.ReqSubmitDeviceInfoBean.LocallyBean
import com.uduew.sjd.api.SubmitDeviceInfoApi.ReqSubmitDeviceInfoBean.SovpreneBean

object NetworkInfoCollector {
    // 获取WiFi列表
    fun getWifiList(context: Context): List<LocallyBean> {
        val wifiList = mutableListOf<LocallyBean>()
        val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager

        // 检查权限
        if (ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return emptyList()
        }

        // 检查WiFi是否启用
//        if (!wifiManager.isWifiEnabled) {
//            wifiManager.isWifiEnabled = true // 可选：自动开启WiFi
//        }

        // 获取扫描结果
        val scanResults = wifiManager.scanResults
        val currentConnection = wifiManager.connectionInfo

        // 获取本机信息
        val localMac = currentConnection.macAddress ?: ""
        val localIp = Formatter.formatIpAddress(currentConnection.ipAddress)

        // 转换数据结构
        scanResults.forEach { result ->
            wifiList.add(
                LocallyBean(
                    result.SSID ?: "Hidden SSID",
                    result.BSSID, result.SSID ?: "",
                    localMac, localIp
                )
            )
        }

        return wifiList
    }

    // 获取当前连接WiFi信息
    fun getCurrentWifi(context: Context): SovpreneBean {
        val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val info = wifiManager.connectionInfo
        return SovpreneBean(
            info.ssid?.removeSurrounding("\"") ?: "",
            info.bssid ?: "",
            info.ssid?.removeSurrounding("\"") ?: "",
            info.macAddress ?: "",
            Formatter.formatIpAddress(info.ipAddress)
        )
    }
}
